//
//  HomeViewController.m
//  ZJControlsClass
//
//  Created by apple on 2024/10/22.
//

#import "HomeViewController.h"
#import <SangforSDK/SFUemSDK.h>


#import "RealNameAlertView.h"
#import "RealNameViewController.h"
#import "ApprovaledViewController.h"
#import "HomeNetWorking.h"

#import "HomeHeaderView.h"
#import "HomeNotiFScrollewView.h"
#import "HomeHeaderScrollView.h"
#import "HomeTableViewCell.h"

#import "HomeBannerModel.h"
#import "HomeShowInfoModel.h"
#import "HomeShowNewsModel.h"


#import "HomeGoodsListViewController.h"
#import "HomeQuestionEcodeDeviceViewController.h"
#import "JMScanningQRCodeUtils.h"





@interface HomeViewController ()<protocolRealNameAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>{
    NSInteger pageNo;
    NSInteger pageSize;
}

@property (nonatomic,strong) UILabel * titileLabel;
@property (nonatomic,strong) RealNameAlertView * alertView;

@property (nonatomic,strong) UIView * KwindowView;


@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) HomeHeaderView * headerView;
@property (nonatomic,strong) HomeNotiFScrollewView * notifView;

@property (nonatomic,strong) HomeGetUserInfoManationNetWorking * manager;
@property (nonatomic,strong) HomeGetBannerNetWorking * bannerManager;
@property (nonatomic,strong) HomeShowNewsNetWorking * showNewsManager;
@property (nonatomic,strong) HomeShowInfoNetWorking * showInfoManager;

@property (nonatomic,strong) NSMutableDictionary * paramer;
@property (nonatomic,strong) NSMutableArray * bannerArr;
@property (nonatomic,strong) NSMutableDictionary * TableViewParamer;
@property (nonatomic,strong) NSMutableArray * newsArr;;



@end

@implementation HomeViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self loadNet];
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    pageNo = 1;
    pageSize = 20;
    
    
    self.KwindowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.KwindowView.backgroundColor = [UIColor blackColor];
    self.KwindowView.alpha = 0.0;
    [kWindow addSubview:self.KwindowView];
    
    [self setUpUI];
    [self loadNet];
    [self getBannaerNet];
    [self getShowInfoManagerNet];
    [self getShowNewsManagerNet];
    
    
    
    
}


#pragma  mark -- 网络请求
-(void)loadNet{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    [self.manager dispatchTaskWithParam:@{@"id":[defaults valueForKey:@"userId"]} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            
            self.paramer = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"data"]];
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:self.paramer[@"nickname"] forKey:@"nickname"];
            [defaults setObject:self.paramer[@"avatar"] forKey:@"avatar"];
            
            
            
            if ([responseObject[@"data"][@"real"] boolValue]){ // 已认证
                self.KwindowView.alpha = 0;
                self.alertView.alpha = 0;
                
                
            }else{ // 未认证
                
                self.KwindowView.alpha = 0.5;
                self.alertView.alpha = 1;
                
                [kWindow addSubview:self.alertView];
                [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(kWindow).with.offset(ALIGN_WIDTH_PT(20));
                    make.right.equalTo(kWindow).with.offset(-ALIGN_WIDTH_PT(20));
                    make.centerY.equalTo(kWindow.mas_centerY);
                    make.height.equalTo(@(ALIGN_HEIGHT_PT(210)));
                }];
                
            }
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"网络请求%@",responseObject[@"msg"]] buttonAction:^{
                
            }];
            
        }
        
        
        
        
    }];
    
}



-(void)getBannaerNet{
    
    [self.bannerManager dispatchTaskWithParam:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            
            self.bannerArr = [NSMutableArray arrayWithArray:responseObject[@"data"]];
            [self.tableView reloadData];
            
            
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"网络请求%@",responseObject[@"msg"]] buttonAction:^{
                
            }];
        }
    }];
    
}


-(void)getShowInfoManagerNet{ // 跑马灯
    
    [self.TableViewParamer setValue:[NSString stringWithFormat:@"%@",@(pageNo)] forKey:@"pageNo"];
    [self.TableViewParamer setValue:[NSString stringWithFormat:@"%@",@(pageSize)] forKey:@"pageSize"];
    [self.showInfoManager dispatchTaskWithParam:self.TableViewParamer completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            
            self.newsArr = [NSMutableArray arrayWithArray:[HomeShowInfoModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]]];
            [self.tableView reloadData];
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"网络请求%@",responseObject[@"msg"]] buttonAction:^{
                
            }];
        }
    }];
}

-(void)getShowNewsManagerNet{ // tableView
    
    [self.showNewsManager dispatchTaskWithParam:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            
            if (self->pageNo == 1) {
                [self.dataSource removeAllObjects];
            }
            NSArray * data = responseObject[@"data"][@"list"];
            if (data.count < 20)[self.tableView.mj_footer endRefreshingWithNoMoreData];
            else [self.tableView.mj_footer endRefreshing];
            [self.dataSource  addObjectsFromArray:[HomeShowNewsModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]]];
               
            [self.tableView reloadData];
            
            
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"网络请求%@",responseObject[@"msg"]] buttonAction:^{
                
            }];
        }
        [self.tableView.mj_header endRefreshing];

    }];
}



-(void)setUpUI{
    
    [self.view addSubview:self.titileLabel];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(StatusBarHeight);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    [self.titileLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset([[UIApplication sharedApplication]statusBarFrame].size.height);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@(44));
    }];
    
}



#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 0;
    }
    return self.dataSource.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 || indexPath.section == 1) {
        return nil;
    }
    
    HomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[HomeTableViewCell cell]];
    if (!cell) {
        cell = [[HomeTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:[HomeTableViewCell cell]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    HomeShowNewsModel * model = self.dataSource[indexPath.row];
    cell.model = model;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 ? ALIGN_HEIGHT_PT(0) : ALIGN_HEIGHT_PT(105);
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        HomeHeaderScrollView * headView = [[HomeHeaderScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ALIGN_HEIGHT_PT(160))];
        headView.dataSource = self.bannerArr;
        
        return headView;
    }else if (section == 1){
        HomeNotiFScrollewView * notif = [[HomeNotiFScrollewView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ALIGN_HEIGHT_PT(60))];
        notif.dataSource = [NSMutableArray arrayWithArray:[HomeShowInfoModel mj_objectArrayWithKeyValuesArray:self.newsArr]];
        
        return notif;
    }else{
        self.headerView = [[HomeHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ALIGN_HEIGHT_PT(190))];
        
        
        return self.headerView;
    }
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    return view;
}




-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0){
        return ALIGN_HEIGHT_PT(160);
    }else if (section == 1){
        return ALIGN_HEIGHT_PT(60);
    }else{
        return ALIGN_HEIGHT_PT(190);
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001;
}



#pragma mark -- 让section跟随tableView一起滚动
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (scrollView == self.tableView) {
//        
//        CGFloat sectionHeaderHeigth = ALIGN_HEIGHT_PT(1000);
//        if (scrollView.contentOffset.y <= sectionHeaderHeigth && scrollView.contentOffset.y >= 0) {
//            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//        }else if (scrollView.contentOffset.y >= sectionHeaderHeigth){
//            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeigth, 0, 0, 0);
//        }
//        
//    }
//}

#pragma mark -- protocolRealNameAlertViewDelegate
-(void)canleRealNameAlertView{
    self.KwindowView.alpha = 0;
    self.alertView.alpha = 0;
    
}

-(void)enterRealNameViewController{
    [self canleRealNameAlertView];
    RealNameViewController * vc = [RealNameViewController new];
    vc.nameStr = self.paramer[@"nickname"];
    vc.idNoStr = self.paramer[@"idNo"];
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark -- 懒加载
-(UILabel *)titileLabel{
    if (!_titileLabel) {
        _titileLabel = [UILabel new];
        _titileLabel.text = @"首页";
        _titileLabel.textColor = [UIColor blackColor];
        _titileLabel.textAlignment = NSTextAlignmentCenter;
        _titileLabel.font = FONT18;
    }
    return _titileLabel;
}

-(RealNameAlertView *)alertView{
    if (!_alertView) {
        _alertView = [RealNameAlertView new];
        _alertView.delegate = self;
        _alertView.alpha = 1;
    }
    return _alertView;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            pageNo = 1;
            [self.TableViewParamer addEntriesFromDictionary:@{@"pageNo":@(pageNo)}];
            [self getShowNewsManagerNet];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            pageNo += 1;
            [self.TableViewParamer addEntriesFromDictionary:@{@"pageNo":@(pageNo)}];
            [self getShowNewsManagerNet];
        }];
    }
    return _tableView;
}
-(NSMutableArray *)dataSource{
    if (!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}



-(HomeGetUserInfoManationNetWorking *)manager{
    if (!_manager){
        _manager = [HomeGetUserInfoManationNetWorking new];
    }
    return _manager;
}

-(HomeGetBannerNetWorking *)bannerManager{
    if (!_bannerManager){
        _bannerManager = [HomeGetBannerNetWorking new];
    }
    return _bannerManager;
}

-(HomeShowNewsNetWorking *)showNewsManager{
    if (!_showNewsManager){
        _showNewsManager = [HomeShowNewsNetWorking new];
    }
    return _showNewsManager;
}

-(HomeShowInfoNetWorking *)showInfoManager{
    if (!_showInfoManager){
        _showInfoManager = [HomeShowInfoNetWorking new];
    }
    return _showInfoManager;
}

-(NSMutableDictionary *)TableViewParamer{
    if (!_TableViewParamer){
        _TableViewParamer = [NSMutableDictionary dictionary];
    }
    return _TableViewParamer;
}


@end
